<!DOCTYPE html>
<%@ taglib prefix="s" uri="/struts-tags"%>
<%@ taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<s:set var="createSuccessfulMsg"
  value="%{getText('info.create.successful', {getText('title.product.attribute')})}" />
<s:set var="requiredMsg" value="%{getText('error.required')}" />
<script type="text/javascript">
  function calculateFinalRetailPrice() {
    var adjustmentRetailPriceEl = $('#product-attribute-add-dialog-form #adjustmentRetailPrice');
    var finalRetailPriceEl = $('#product-attribute-add-dialog-form #finalRetailPrice');
    var baseRetailPrice = $('#product-attribute-add-dialog-form #baseRetailPrice').val();
    var adjustmentRetailPrice = adjustmentRetailPriceEl.val();
    adjustmentRetailPrice = $.isNumeric(adjustmentRetailPrice) ? adjustmentRetailPrice : 0;
    var finalRetailPrice = parseFloat(baseRetailPrice) + parseFloat(adjustmentRetailPrice);
    finalRetailPriceEl.text(finalRetailPrice);
  }

  function refreshProduct() {
    jQuery.ajax({
      url : '${pageContext.request.contextPath}/inventory/product/loadProduct.action',
      dataType : 'json',
      async : false,
      cache : false,
      data : {
        'product.id' : $('#id').val()
      },
      success : function(data) {
        var name = data.name;
        var categories = data.categories;
        var length = categories.length;
        var baseRetailPrice = data.baseRetailPrice;
        $('#product-attribute-add-dialog-form #productName').text(name);
        var categ = '';
        for ( var i = 0; i < length; i++) {
          categ += categories[i].name;
          categ += (i < length - 1 ? ', ' : '');
        }
        $('#product-attribute-add-dialog-form #categories').text(categ);
        $('#product-attribute-add-dialog-form #baseRetailPriceLbl').text(baseRetailPrice);
        $('#product-attribute-add-dialog-form #baseRetailPrice').val(baseRetailPrice);
        calculateFinalRetailPrice();
      }
    });
  }
  function resetForm() {
    $('#product-attribute-add-dialog-form :input:not(:hidden)').val('');
    calculateFinalRetailPrice();
    focusOnFirstElement();
  }

  function focusOnFirstElement() {
    setTimeout(function() {
      $('#product-attribute-add-dialog-form :input:visible:enabled:first').focus();
    },10);
  }

  $(function() {
    $('#product-attribute-add-dialog-form :input:not(:hidden)').prop('autocomplete','off');
    $('#productAttributeAddMsg').tooltip({
      tooltipClass : "ui-state-highlight"
    });
    $('#addProductAttributeButtonDiv').addClass('ui-dialog-buttonset');
    $('#product-attribute-add-dialog-form .submit-button').button();
    $('#product-attribute-add-dialog-form  #adjustmentRetailPrice').keyup(function() {
      refreshProduct();
    });
    
    $('#productAttributeOkBtn')
        .click(
            function(e) {
              e.preventDefault();
              var bValid = $('#product-attribute-add-form').valid();
              if (bValid) {
                var params = {};
                params['productAttribute.productId'] = $(
                    '#product-attribute-add-dialog-form #productId').val();
                params['productAttribute.attributeName'] = $(
                    '#product-attribute-add-dialog-form #attributeName').val();
                params['productAttribute.sku'] = $('#product-attribute-add-dialog-form #sku').val();
                params['productAttribute.adjustmentRetailPrice'] = $(
                    '#product-attribute-add-dialog-form #adjustmentRetailPrice').val();
                jQuery
                    .ajax({
                      url : '${pageContext.request.contextPath}/inventory/productAttribute/createProductAttribute.action',
                      type : 'POST',
                      dataType : 'json',
                      cache : false,
                      data : params,
                      success : function(data) {
                        var msg = '';
                        var status = data.status;
                        if (status == 'SUCCESS') {
                          msg = '<s:property value="#createSuccessfulMsg"/>';
                          resetForm();
                        } else if (status == 'ERROR') {
                          if (data.errors) {
                            var errors = data.errors;
                            for ( var i = 0; i < errors.length; i++) {
                              msg += errors[i];
                              if (i < errors.length - 1) {
                                msg += ', ';
                              }
                            }
                          }
                        }
                        $('#productAttributeAddMsg').attr('title',msg).tooltip('open');
                        setTimeout(function() {
                          $('#productAttributeAddMsg').tooltip("close").attr("title","");
                        },1500);
                      }
                    });
              }
            });
    $('#productAttributeCancelBtn').click(function(e) {
      e.preventDefault();
      $('#listProductAttribute').trigger('reloadGrid');
      $('#productAttributeEditDialog').empty();
      $('#product-view-dialog-form').show();
    });
    $("#productAttributeAddAccordion").multipleaccordion();
    $('#productAttributeAddAccordion > div > table td.LABEL').css({
      'width' : '130px'
    });
    $('#product-attribute-add-dialog-form input, select, textarea, button').not(':hidden').each(
        function(idx) {
          $(this).prop('tabindex',idx + 1);
        });
    $('#product-attribute-add-dialog-form').wrap('<form id="product-attribute-add-form">');
    $.validator.setDefaults({
      errorClass : 'ui-state-error',
      errorPlacement : function(error,element) {
        if (element.context.id.indexOf('_combobox') == -1) {
          error.insertAfter(element.parent().children(':last'));
        } else {
          error.appendTo(element.parent());
        }
      }
    });
    $('#product-attribute-add-form').validate(
        {
          rules : {
            'attributeName' : {
              required : true
            },
            'sku' : {
              required : true
            },
            'adjustmentRetailPrice' : {
              required : true,
              number : true,
            }
          },
          messages : {
            'attributeName' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.product.attribute.name\")}" />')
            },
            'sku' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.stock.keeping.unit\")}" />')
            },
            'adjustmentRetailPrice' : {
              required : jQuery.format('<s:property value="#requiredMsg" />',
                  '<s:property value="%{getText(\"field.adjustment.retail.price\")}" />'),
              number : jQuery.format('<s:property value="getText(\'error.numeric.required\')" />',
                  '<s:property value="%{getText(\"field.adjustment.retail.price\")}" />')
            }
          }
        });
    refreshProduct();
    focusOnFirstElement();
  });
</script>
<div id="product-attribute-add-dialog-form"
  title='<s:property value="getText('title.add.product.attribute')"/>'>
  <div id="productAttributeAddMsg"></div>
  <div id="productAttributeAddAccordion">
    <h3>
      <s:property value="getText('title.product.attribute')" />
    </h3>
    <div>
      <table>
        <tr>
          <td class="LABEL"><label> <s:property value="getText('field.product.name')" /></label></td>
          <td><label id="productName"></label></td>
        </tr>
        <tr>
          <td class="LABEL"><label> <s:property
                value="getText('field.product.category.name')" /></label></td>
          <td><label id="categories"></label></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="attributeName" class="mandatory"><input
              type="hidden" id="productId" name="productAttribute.productId"
              value='<s:property value="%{#parameters[\"productAttribute.productId\"]}" />' /> <s:property
                value="getText('field.product.attribute.name')" /></label></td>
          <td><input type="text" id="attributeName" name="attributeName" maxlength="100" /></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="sku" class="mandatory"><s:property
                value="getText('field.stock.keeping.unit')" /></label></td>
          <td><input type="text" id="sku" name="sku" maxlength="100" /></td>
        </tr>
        <tr>
          <td class="LABEL"><label> <s:property
                value="getText('field.base.retail.price')" /></label></td>
          <td><label id="baseRetailPriceLbl"></label><input type="hidden" id="baseRetailPrice"
            name="baseRetailPrice" /></td>
        </tr>
        <tr>
          <td class="LABEL"><label for="adjustmentRetailPrice" class="mandatory"><s:property
                value="getText('field.adjustment.retail.price')" /></label></td>
          <td><input type="text" id="adjustmentRetailPrice" name="adjustmentRetailPrice"
            maxlength="100" value="0" /></td>
        </tr>
        <tr>
          <td class="LABEL"><label> <s:property value="getText('field.retail.price')" /></label></td>
          <td><label id="finalRetailPrice"></label></td>
        </tr>
      </table>
    </div>
  </div>
  <div id="addProductAttributeButtonDiv">
    <button id="productAttributeOkBtn" class="submit-button">
      <s:property value="getText('button.ok')" />
    </button>
    <button id="productAttributeCancelBtn" class="submit-button">
      <s:property value="getText('button.cancel')" />
    </button>
  </div>
</div>
